package cn.dakaqi.utils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;


/**
 *
 * @author $author$
 * @version $Revision$
 */
public class PicCheckCode extends HttpServlet {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public static final String CODE_IN_SESSION="getImgOnFood";
	
	private Font[] mFonts     = {
			new Font(Font.SANS_SERIF, Font.PLAIN, 20),
			new Font(Font.SANS_SERIF, Font.ITALIC,18),
			new Font(Font.SANS_SERIF, Font.ITALIC,20),
			new Font(Font.SANS_SERIF, Font.PLAIN,18)};
	
	private String[] joinStr = {"加","减","乘"};
	private String numsStr[] = {"零","壹","贰","叁","四","五","六","七","八","九","拾"};
    private int  width     = 120; //定义图形大小
    private int  height    = 40; //定义图形大小
    private int  count     = 10;
    
    private Random random = new Random();


    /**
     * 描述：
     *
     * @param fc 描述：
     * @param bc 描述：
     *
     * @return 描述：
     */
    private Color getRandColor(int fc, int bc) { //取得给定范围随机颜色

        if (fc > 255) {

            fc = 255;
        }

        if (bc > 255) {

            bc = 255;
        }

        int r = fc + random.nextInt (bc - fc);
        int g = fc + random.nextInt (bc - fc);
        int b = fc + random.nextInt (bc - fc);
        
        return new Color(r, g, b);
    }

    //处理post
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        doGet (request, response);
    }

    /**
     * 描述：
     *
     * @param request 描述：
     * @param response 描述：
     *
     * @throws javax.servlet.ServletException 描述：
     * @throws java.io.IOException 描述：
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        //response.reset();
        //设置页面不缓存
        response.setHeader ("Pragma", "No-cache");
        response.setHeader ("Cache-Control", "no-cache");
        response.setDateHeader ("Expires", 0);
        response.setContentType ("image/gif");

        // 在内存中创建图象
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);

        // 获取图形上下文
        Graphics2D g = (Graphics2D) image.getGraphics ();

        // 设定背景色
        g.setColor (getRandColor (240, 250)); //---1

        g.fillRect (0, 0, width, height);

        //画边框
        g.setColor (new Color(225,225,225)); //---2
        g.drawRect (0, 0, width - 1, height - 1);

        //随机产生干扰线，使图象中的认证码不易被其它程序探测到
        for (int i = 0; i < count; i++) {

            g.setColor (getRandColor (150, 200)); //---3

            int x  = random.nextInt (20) + 1; //保证画在边框之内
            int y  = random.nextInt (39)+1;
            int xl = random.nextInt (20)+100;
            int yl = random.nextInt (39)+1;
            g.drawLine (x, y,xl,yl);
        }

        int num1 = random.nextInt(numsStr.length);
        int num2 =  random.nextInt(numsStr.length);
        int join = random.nextInt(numsStr.length)%joinStr.length;
        
      
        
        //初始化 join ==0 的状态，其他情况在switch中做特殊处理
        String sessionResult = (num1+num2)+"";
        String[] picStrs = {numsStr[num1],joinStr[join],numsStr[num2],"等于？"};  
        switch(join){
	        case 1:
	        	if(num1>num2){
		        	sessionResult = (num1-num2)+"";
	        	}else{
	        		sessionResult = (num2-num1)+"";
	        		
	        		picStrs[0] = numsStr[num2];
		        	picStrs[2] = numsStr[num1];
	        	}
	        	
	        	break;
	        case 2:
	        	sessionResult = (num1*num2)+"";
	        	break;
	    }
        
        
       // log.info("new Code Is ："+sessionResult);
        
        int nums = mFonts.length;
        for (int i = 0; i < picStrs.length; i++) {

            String str = picStrs[i];

            // 将认证码显示到图象中,调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成
           // g.setColor (new Color(170+random.nextInt(85),0+random.nextInt(100),0+random.nextInt(120))); //--4--50-100
          
            g.setColor (new Color(20 + random.nextInt (130),
                    20 + random.nextInt (130), 20 + random.nextInt (130))); //--4--50-100
            
            g.setFont (mFonts[random.nextInt(nums)]);
            g.drawString (str, 5+random.nextInt(5)+(18 * i),random.nextInt(10)+25);

            
        }
        
        //System.out.println("----sRand :"+sRand);

        // 将认证码存入SESSION
        request.getSession ().setAttribute (CODE_IN_SESSION,sessionResult);

        // 图象生效
        g.dispose ();

        // 输出图象到页面
        ImageIO.write (image, "PNG", response.getOutputStream ());
    }
}

